﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using Pahan.McuFusion.Common;
using Pahan.McuFusion.Common.Serialization;

namespace Pahan.McuFusion.FusionBoot.Atmel.AVR
{
    [Serializable]
    [DeviceInfoSurrogate(typeof(AvrMcuInfoSurrogate))]
    public class AvrMcuInfo : FusionBootMcuInfo
    {
        #region Construction and Initialization

        protected internal AvrMcuInfo(String model, IList<byte> modelCode, params MemoryClassInfo[] memory)
        {
            this.model = model;
            this.modelCode = modelCode;
            this.memory = new ReadOnlyCollection<MemoryClassInfo>(memory);
        }

        public static IList<FusionBootMcuInfo> GetAllDevices()
        {
            if (devices == null)
            {
                var reader = new JsonDeviceInfoListReader<AvrMcuInfo>();
                var dir = Path.GetDirectoryName(
                    Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName);
                var path = Path.Combine(dir, "FusionBoot.Atmel.AVR.json");
                devices = reader.ReadList(path).OrderBy(d => d.Model).Cast<FusionBootMcuInfo>().ToList();
            }

            return devices;
        }

        #endregion

        #region Overrides of DeviceInfo

        public sealed override string Vendor
        {
            get
            {
                return "Atmel";
            }
        }

        public sealed override string Model
        {
            get
            {
                return model;
            }
        }

        public override IList<MemoryClassInfo> Memory
        {
            get
            {
                return memory;
            }
        }

        #endregion

        #region Overrides of FusionBootMcuInfo

        public override IList<byte> ModelCode
        {
            get
            {
                return modelCode;
            }
        }

        #endregion

        #region Private Members

        private readonly String model;

        private readonly IList<MemoryClassInfo> memory;

        private readonly IList<byte> modelCode;

        private static IList<FusionBootMcuInfo> devices;

        #endregion
    }
}
